import SDKAd from "./SDKAd";
import { ResultCallback, SDKState } from "../SDKDefine";

/**
 * 插屏广告
 * wx:每次调用该方法创建插屏广告都会返回一个全新的实例
 * https://developers.weixin.qq.com/minigame/dev/api/ad/wx.createInterstitialAd.html
 */
export default class SDKInterstitialAd extends SDKAd {

    protected callback: ResultCallback;


    preload(logicState: SDKState) {
        this._logicState = logicState;
        this.destroy();
        this.create();
        this.load(null);
    }

    open(func?: ResultCallback) {
        this.callback = func;
        this._state = SDKState.LOADING;
        this.destroy()
        this.create()
        this.show()
    }


    onClose() {

    }

    create() {
        // 创建插屏广告实例，提前初始化
        if (!this.instance) {
            this.instance = this.sdk.createInterstitialAd({
                adUnitId: this._adUnitId
            })
            this.instance.onLoad(this.bind(this.onLoad))
            this.instance.onError(this.bind(this.onError))
            this.instance.onClose(this.bind(this.onClose))
        }
    }

    onLoad() {
        this.setState(SDKState.SUCCESS)
        if (this.callback) {
            this.callback(SDKState.SUCCESS)
            this.callback = null;
        }
        if (this._logicState == SDKState.OPEN) {
            this._logicState = SDKState.CLOSE;
            this.show()
        }

    }

    show() {
        if (this.instance) {
            this.instance.show()
        }
    }

    load(func?: ResultCallback) {
        this.callback = func;
        if (this.instance) {
            this.instance.load();
        }
    }

    onError(err) {
        this.setState(SDKState.FAIL)
        if (this.callback) {
            this.callback(SDKState.FAIL)
            this.callback = null;
        }
        if (err && err.errCode) {

        }

    }

    destroy() {
        if (this.instance) {
            this.instance.offLoad(this.unbind(this.onLoad))
            this.instance.offError(this.unbind(this.onError))
            this.instance.offClose(this.unbind(this.onClose))
            this.instance.destroy()
            this.instance = null;
        }
    }
}
